<template>
  <div class="table-box">
    <ProTable
        ref="proTable"
        title="分类列表"
        :columns="columns"
        :pagination="false"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'/cate/add'" type="primary" :icon="CirclePlus" @click="openDrawer('新增', { pid: '' })">
          新增分类
        </el-button>
        <el-button
            v-auth="'/cate/delete/*'"
            type="danger"
            :icon="Delete"
            plain
            :disabled="!scope.isSelected"
            @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- icon_name -->
      <template #icon_name="scope">
        <el-icon v-if="scope.row.icon_name && scope.row.icon_type == 1" style="font-size: 18px">
          <component :is="scope.row.icon_name"></component>
        </el-icon>
        <i v-if="scope.row.icon_name && scope.row.icon_type == 2" class="el-icon iconfont" :class="scope.row.icon_name" />
      </template>
      <!-- sort -->
      <template #sort="scope">
        <el-input-number
            size="small"
            :model-value="scope.row.sort"
            :disabled="!authButton('/cate/changeSort')"
            @change="(val: number) => changeSort(val, scope.row)"
        />
      </template>
      <!-- status -->
      <template #status="scope">
        <el-switch
            :model-value="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            :disabled="!authButton('/cate/change_status/*')"
            @click="changeStatus(scope.row)"
        />
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" v-auth="'/cate/edit/*'" @click="openDrawer('编辑', scope.row)"
        >编辑</el-button
        >
        <el-button type="danger" link :icon="Delete" v-auth="'/cate/delete/*'" @click="delCate(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <CateDrawer ref="drawerRef" />
  </div>
</template>

<script lang="ts">
export default {
  name: "cateManage",
};
</script>

<script setup lang="ts">
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import CateDrawer from "@/views/app/cate/CateDrawer.vue";
import ProTable from "@/components/ProTable/index.vue";
import { reactive, ref } from "vue";
import { cate } from "./cate";
import { ProTableInstance } from "@/components/ProTable/interface";
import {
  addCateApi,
  changeSortApi,
  changeStatusApi,
  cateTreeApi,
  deleteCateByIdApi,
  deleteCateApi,
  editCateApi,
} from "@/api/modules/cate.ts";
import { useHandleData } from "@/hooks/useHandleData.ts";
import { authButton } from "@/hooks/useAuthButton.ts";
import { Recordable } from "@/interface/types.ts";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
const cateTree = ref<any[]>([]);

const { columns } = cate(cateTree.value);

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.create_time && (newParams.startTime = newParams.create_time[0]);
  newParams.create_time && (newParams.endTime = newParams.create_time[1]);
  delete newParams.create_time;
  return cateTreeApi(newParams);
};

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  cateTree.value = data as any[];
  proTable.value?.updateSearchColumn({ key: "pid", data: data });
  return data;
};

// 打开 dialog(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: Partial<Recordable> = {}) => {
  console.log(rowData);
  let params = {
    title,
    rowData: { ...rowData },
    isView: title === "查看",
    cateTree: cateTree.value,
    api: title === "新增" ? addCateApi : title === "编辑" ? editCateApi : "",
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value.acceptParams(params);
};

// 删除分类信息
const delCate = async (row: Recordable) => {
  await useHandleData(deleteCateByIdApi, row.id, `删除【${row.name}】分类`);
  proTable.value?.getTableList();
};

// 批量删除分类信息
const batchDelete = async (pds: string[]) => {
  await useHandleData(deleteCateApi, { pds }, "删除所选分类信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 修改分类排序
const changeSort = async (val: number, row: Recordable) => {
  if (!authButton("/cate/changeSort")) {
    return;
  }
  await useHandleData(changeSortApi, { id: row.id, sort: val }, `修改【${row.name}】分类排序`);
  proTable.value.getTableList();
};

// 切换状态
const changeStatus = async (row: Recordable) => {
  if (!authButton("/cate/change_status/*")) {
    return;
  }
  await useHandleData(changeStatusApi, row.id, `切换【${row.name}】分类状态`);
  proTable.value?.getTableList();
};
</script>

<style scoped lang="scss"></style>
